package version3.part2.common.serializer.MySerializer.impl;

import version3.part2.common.serializer.MySerializer.Serializer;

import java.io.*;

public class JDKSerializer implements Serializer {
    @Override
    public byte[] serialize(Object data) {
        byte[] bytes = null;
        // data -> oos -> baos -> bytes
        // try-with-resources 自动释放资源
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(data);
            oos.flush();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Object deserialize(byte[] bytes, int messageType) {
        Object obj = null;
        // bytes -> bais -> ois -> obj
        try(ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais) ){
            // 反序列化
            obj = ois.readObject();
            return obj;
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    @Override
    public int getType() {
        return 0;
    }
}
